package com.enjoylearning.learning.service.impl;

import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.base.model.RestResponse;
import com.enjoylearning.content.model.dto.TeachplanDto;
import com.enjoylearning.content.model.po.CoursePublish;
import com.enjoylearning.content.model.po.Teachplan;
import com.enjoylearning.learning.feignclient.ContentServiceClient;
import com.enjoylearning.learning.feignclient.MediaServiceClient;
import com.enjoylearning.learning.mapper.XcCourseTablesMapper;
import com.enjoylearning.learning.model.dto.XcCourseTablesDto;
import com.enjoylearning.learning.service.LearningService;
import com.enjoylearning.learning.service.MyCourseTablesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class LearningServiceImpl implements LearningService {

    @Autowired
    private MyCourseTablesService myCourseTablesService;
    @Autowired
    private ContentServiceClient contentServiceClient;
    @Autowired
    private MediaServiceClient mediaServiceClient;

    @Override
    public RestResponse<String> getVideo(String userId, Long courseId, Long teachplanId, String mediaId) {
        CoursePublish coursepublish = contentServiceClient.getCoursepublish(courseId);
        if (coursepublish == null) {
            XueChengPlusException.cast("课程未发布");
        }
        //查询课程计划
        List<TeachplanDto> teachplanDtos = contentServiceClient.selectTeachPlanById(courseId);
        if (teachplanDtos.isEmpty()) {
            return RestResponse.validfail("该课程计划为空");
        }
        //判断是否登录
        if (userId.isEmpty()){
            //未登录，取出收费规则
            String charge = coursepublish.getCharge();
            //免费课程且支持试学，可学习
            Optional<TeachplanDto> isPreview = teachplanDtos.stream().filter(e -> e.getId() == 1).findFirst();
            if (charge.equals("201001") && isPreview.get().getIsPreview().equals("1")){
                RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
                return playUrlByMediaId;
            }
            //收费课程
            return RestResponse.validfail("请先登录");
        }
        //获取学习资格
        XcCourseTablesDto learningStatus = myCourseTablesService.getLearningStatus(userId, courseId);
        if (learningStatus.getLearnStatus().equals("702002")){
            return RestResponse.validfail("没有选课或选课后没有支付");
        }
        if (learningStatus.getLearnStatus().equals("702003")){
            return RestResponse.validfail("课程有效期已过，请续费后进行学习");
        }
        //有学习资格后远程调用媒资服务获取视频地址
        RestResponse<String> playUrlByMediaId = mediaServiceClient.getPlayUrlByMediaId(mediaId);
        return playUrlByMediaId;
    }
}
